<template>
  <div class="task-form">
    <el-form :model="taskForm" :rules="rules" ref="taskFormRef" label-width="120px">
      <el-form-item label="任务名:" prop="name">
        <el-input v-model="taskForm.name" @blur="handleBlur('name')"></el-input>
      </el-form-item>
      <el-form-item label="任务类型:" prop="type">
        <el-input v-model="taskForm.type" @blur="handleBlur('type')"></el-input>
      </el-form-item>
      <el-form-item label="负责人:" prop="assignedTo">
        <el-input v-model="taskForm.assignedTo" @blur="handleBlur('assignedTo')"></el-input>
      </el-form-item>
      <el-form-item label="截止时间:">
        <el-date-picker v-model="taskForm.endTime" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="任务描述:">
        <el-input type="textarea" v-model="taskForm.taskDescription"></el-input>
      </el-form-item>
      <el-form-item label="附件:" width="200">
      </el-form-item>
      <el-form-item label="">
        <el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          :limit="3"
          :file-list="fileList"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          list-type="text"
          multiple>
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('taskFormRef')">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios' 

const router = useRouter()
const route = useRoute()

const taskForm = ref({
  name: '',
  type: '',
  assignedTo: '',
  endTime: '',
  taskDescription: '',
  projectId: ''
})

const rules = {
  name: [
    { required: true, message: '任务名不能为空', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '任务类型不能为空', trigger: 'blur' }
  ],
  assignee: [
    { required: true, message: '负责人不能为空', trigger: 'blur' }
  ]
}

const taskFormRef = ref(null)

const mode = ref(route.params.mode)
const projectId = ref(route.params.projectId)
const task = ref(route.query.task ? JSON.parse(route.query.task) : {})

onMounted(() => {
  if (mode.value === 'edit' && task.value) {
    taskForm.value = { ...task.value }
    console.log(taskForm.value)
  }
})

const submitForm = (formName) => {
  taskFormRef.value.validate((valid) => {
    if (valid) {
      saveTask()

    } else {
      handleInvalidFields()
      console.log('表单验证失败')
      return false
    }
  })
}

const handleInvalidFields = () => {
  const invalidFields = taskFormRef.value.fields
  for (let key in invalidFields) {
    if (invalidFields[key].validateState === 'error') {
      const element = invalidFields[key].$el.querySelector('.el-input__inner')
      element.classList.add('shake')
      setTimeout(() => {
        element.classList.remove('shake')
      }, 500)
    }
  }
}

const saveTask = async () => {
  console.log(mode.value)
  taskForm.value.projectId = projectId.value
  if (mode.value === 'create') {
    // 添加新的任务逻辑
    await axios.post('http://localhost:8080/tasks/save', taskForm.value)
    ElMessage.success('任务创建成功')
  } else if (mode.value === 'edit') {
    // 更新已有任务逻辑
    await axios.put('http://localhost:8080/tasks/update', taskForm.value)
    ElMessage.success('任务更新成功')
  }
  console.log(taskForm.value)
  router.push({ name: 'project-management', params: { id: projectId.value}  })
}

const cancel = () => {
  router.push({ name: 'project-management', params: { id: projectId.value} })
}

const handleBlur = (prop) => {
  taskFormRef.value.validateField(prop)
}

const handlePreview = (file) => {
  console.log('preview', file)
}

const handleRemove = (file, fileList) => {
  console.log('remove', file, fileList)
}

const beforeUpload = (file) => {
  return true
}
</script>

<style scoped>
.task-form {
  padding: 20px;
}

@keyframes shake {
  0% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  50% { transform: translateX(5px); }
  75% { transform: translateX(-5px); }
  100% { transform: translateX(0); }
}

.shake {
  animation: shake 0.5s;
}
</style>
